package com.jt.service.impl;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.logging.Logger;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    private static final String KEY_PREFIX = "menu:";

    /*注入方案1 */
//    @Autowired
//    private RedisTemplate redisTemplate;
//
//    @Autowired
//    private MenuMapper menuMapper;



    private MenuMapper menuMapper;
    private ValueOperations valueOperations;

    public MenuServiceImpl(MenuMapper menuMapper,
                           @Qualifier("redisTemplate") RedisTemplate redisTemplate11) {
        this.menuMapper = menuMapper;
        this.valueOperations = redisTemplate11.opsForValue();
    }
//    private static final



    @Override
    public Menu selectById(Long id) {
        //1.从redis中获取菜单信息，有则直接返回
//        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object obj = valueOperations.get("menu:" + id);
        if (obj != null){
            log.info("Data from Redis Cache");
            return (Menu) obj;
        }
        //2.从mysql数据库中查询菜单信息
        log.info("Data from MySQL");
        Menu menu = menuMapper.selectById(id);
        //3.将数据中查询到的菜单信息存储到redis
        valueOperations.set("menu:"+id, menu, Duration.ofSeconds(60*60));
        //4.返回查询到的数据
        return menu;
    }

    @Override
    public Menu insertMenu(Menu menu) {
        //1.保存到关系数据
        log.info("insert.before.menu={}",menu);
        menuMapper.insert(menu);
        log.info("insert.after.menu={}",menu);
        //2.将数据保存到缓存
//        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(),menu);
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
        //1.更新mysql
        menuMapper.updateById(menu);
        //2.更新redis缓存
//        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(),menu);
        return menu;
    }
}
